package com.datastructure.list;

public class DoubleLinkedList implements MyList{
    StudentNode head;
    DoubleLinkedList() {
        head = new StudentNode("",0);
    }
    @Override
    public int get(String name) {
        return 0;
    }

    @Override
    public void add(StudentNode studentNode) {
        StudentNode temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = studentNode;
        studentNode.pre = temp;
    }

    @Override
    public void update(StudentNode studentNode) {
        StudentNode temp = head.next;
        while (temp != null) {
            if (temp.name.equals(studentNode.name)) {
                break;
            }
            temp = temp.next;
        }
        if (temp != null) {
            System.out.println("学生 " + studentNode.name
                    + " 的分数从 " + temp.score + " 更新为 " + studentNode.score);
            temp.score = studentNode.score;
        } else {
            System.out.println("学生 " + studentNode.name + " 不存在");
        }
    }

    @Override
    public void del(String name) {
        StudentNode temp = head.next;
        while (temp != null) {
            if (temp.name.equals(name)) {
                break;
            }
            temp = temp.next;
        }
        if(temp != null) {
            temp.pre.next = temp.next;
            if (temp.next != null) {
                temp.next.pre = temp.pre;
                temp.next = null;
            }
            temp.pre = null;
            System.out.println(name + "已被删除");
        }else {
            System.out.println(name + "不在链表中");
        }
    }

    @Override
    public void show() {
        System.out.println("当前链表为：");
        StudentNode temp = head.next;//从第一个数据节点开始展示
        if (temp == null) {
            System.out.println("空链表");
            return;
        }
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    @Override
    public void addByScore(StudentNode studentNode) {
        StudentNode temp = head.next;
        while (temp != null) {
            //当前节点是最后一个节点 或 目标节点的分数大于后一个节点
            if(temp.score < studentNode.score) {
                break;
            }
            temp = temp.next;
        }
        //节点插入，先将目标节点的next指向temp.next
        //再将 temp.next 指向目标节点
        studentNode.next = temp;
        studentNode.pre = temp.pre;
        temp.pre.next = studentNode;
        temp.pre = studentNode;
    }
}

